package com.yupi.soulba.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.soulba.common.BaseResponse;
import com.yupi.soulba.common.ErrorCode;
import com.yupi.soulba.common.ResultUtils;
import com.yupi.soulba.exception.BusinessException;
import com.yupi.soulba.model.domain.User;
import com.yupi.soulba.model.dto.TeamQuery;
import com.yupi.soulba.model.dto.UserQuery;
import com.yupi.soulba.model.request.UserLoginRequest;
import com.yupi.soulba.model.request.UserRegisterRequest;
import com.yupi.soulba.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yupi.soulba.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 *
 * @author 黄云杰、过江辉
 */
@RestController
@RequestMapping("/user")

@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


     /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String username = userRegisterRequest.getUsername();
        String profile = userRegisterRequest.getProfile();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }
        long result = userService.userRegister(userAccount, username, profile, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户（前端请求）
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        User currentUser = (User) userObj;
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 根据用户名模糊匹配 搜索用户列表
     * @param username
     * @return
     */
    @GetMapping("/search/username")
    public BaseResponse<List<User>> searchUsers(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 根据关键词模糊匹配 username profile tags 搜索用户列表
     * @param searchText
     * @return
     */
    @GetMapping("/search/text")
    public List<User> searchUsersBySearchText(String searchText) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 根据searchText对 username profile tags 三个字段进行模糊查询
        queryWrapper.like("username", searchText)
                .or().like("profile", searchText)
                .or().like("tags", searchText);
        List<User> userList = userService.list(queryWrapper)
                .stream()
                .map(user -> userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return userList;
    }

    /**
     * 通过标签搜索用户列表
     * @param tagNameList
     * @return
     */
    @GetMapping("/search/tags")
    public List<User> searchUsersByTags(List<String> tagNameList) {
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return userList;
    }

    /**
     * 通过关键词和标签搜索用户
     * @param userQuery
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUserBySearchTextAndTags(UserQuery userQuery) {
        List<String> tagNameList = userQuery.getTagNameList();
        String searchText = userQuery.getSearchText();
        List<User> userList = new ArrayList<>();
        // 去重与否的标识 默认去重
        boolean flag = true;
        // 根据关键词模糊查询
        if(StringUtils.isNotEmpty(searchText)) {
            List<User> userListBySearchText = this.searchUsersBySearchText(searchText);
            userList.addAll(userListBySearchText);
        }
        // 如果前一个搜索结果为空 则无必要去重
        if(CollectionUtils.isEmpty(userList)) {
            flag = false;
        }
        // 根据标签查询查询
        if(!CollectionUtils.isEmpty(tagNameList)) {
            List<User> userListByTags = this.searchUsersByTags(tagNameList);
            userList.addAll(userListByTags);
        }
        if(flag) {
            // 将合并列表去重
            return ResultUtils.success(userList.stream().distinct().collect(Collectors.toList()));
        } else {
            // 不用去重则直接返回
            return ResultUtils.success(userList);
        }
    }

    /**
     * 主页推荐用户
     * @param pageSize
     * @param pageNum
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        ValueOperations<String, Object> redisValueOperations = redisTemplate.opsForValue();
        User loginUser = userService.getLoginUser(request);
        // 如果有缓存，直接读缓存
        String redisKey = String.format("soulBa:user:recommend:%s", loginUser.getId());
        Page<User> userPageList = (Page<User>) redisValueOperations.get(redisKey);
        if(userPageList != null){
            return ResultUtils.success(userPageList);
        }
        // redis没有缓存，查数据库，并把数据存入缓存
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 去掉当前登录用户
        queryWrapper.ne("id", loginUser.getId());
        userPageList = userService.page(new Page<>(pageNum, pageSize),queryWrapper);
        try {
            redisValueOperations.set(redisKey, userPageList, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return ResultUtils.success(userPageList);
    }

    /**
     * 匹配最推荐用户
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if(num <= 0 || num >20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "匹配数量参数有误");
        }
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, loginUser));
    }
    
    /**
     * 修改用户信息
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request){
        //校验参数是否为空
        if(user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Integer result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录（非前端）
     * @param request
     * @return
     */
    @GetMapping
    public User getLoginUser(HttpServletRequest request){
        return userService.getLoginUser(request);
    }

    /**
     * 根据id删除用户
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 初始/更新标签
     * @param updateTags
     * @param request
     * @return
     */
    @PostMapping("/tag/update")
    public BaseResponse<Integer> updateTag(@RequestBody String updateTags, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if(loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.updateTagByUserId(updateTags, loginUser.getId());
        return ResultUtils.success(result);
    }

    /**
     * 根据队伍Id查看成员列表
     * @param viewTeamId
     * @return
     */
    @GetMapping("/team/members")
    public BaseResponse<List<User>> viewTeamMembers(Long viewTeamId) {
        if(viewTeamId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "想要查看成员的队伍不存在");
        }
        return ResultUtils.success(userService.viewTeamMembers(viewTeamId));
    }
}
